package com.isljj.web_chat2.controller;

import com.isljj.web_chat2.constant.Constant;
import com.isljj.web_chat2.mapper.*;
import com.isljj.web_chat2.model.*;
import com.isljj.web_chat2.utils.AliOSSUtils;
import com.isljj.web_chat2.utils.JWTUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@RestController
public class SessionController {
    @Autowired
    private SessionMapper sessionMapper;
    @Autowired
    private FriendMapper friendMapper;
    @Autowired
    private UserSessionMapper userSessionMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserMessageMapper userMessageMapper;
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private JWTUtils jwtUtils;
    @Autowired
    private AliOSSUtils aliOSSUtils;
//    删除历史记录
    @RequestMapping("/deleteMessage")
    public Result<Boolean> deleteMassage(Integer sessionId,HttpServletRequest request){
        //拿到登录用户Id
        //TODO 如果另一个人也删了,就删message
        String jwtToken = request.getHeader(Constant.REQUEST_TOKEN_KEY);
        User loginUser = jwtUtils.getUserByToken(jwtToken);
        log.info("登录用户 -" + loginUser.getUserId());
        log.info("登录用户 -" + sessionId);
//       不能删除会话
//       逻辑删除
//        if(ret==0){
//            return new Result<>(-1,"删除历史记录失败",false);
//        }else {
//            return new Result<>(200,"删除历史记录成功",true);
//        }
//        查询这个session所有messageId 到列表
        List<Integer> messageList =  messageMapper.selectMessages(sessionId);
        log.info("messageList - "+messageList.toString());
//        把列表都插入到message
        userMessageMapper.insert(messageList, loginUser.getUserId());

        return  new Result<>(200,"成功",true);
    }

    @RequestMapping("/upload")
    public String upload(@RequestParam MultipartFile file) throws IOException {
        //拿到文件,存储到oss中
        log.info("文件上传 ,文件名"+ file.getOriginalFilename());
        //调用阿里云工具
        String url = aliOSSUtils.upload(file);
        log.info("文件url={}"+url);
        //插入聊天记录
        return url;
    }

    //点击会话标签,查询会话,和会话的最新一条消息  新建一个返回类 包括session 和 最新的一条消息
    @RequestMapping("/sessionList")
    private Result<List> getSessionList(HttpServletRequest request){

        List<SessionLastMessage> sessionLastMessages = new ArrayList<>();
//      先拿到登录用户信息

        String jwtToken = request.getHeader(Constant.REQUEST_TOKEN_KEY);
        //log.info("jwtToken - "+jwtToken);

        User user = jwtUtils.getUserByToken(jwtToken);

        List<Integer> sessionsId =  sessionMapper.getSessionList(user.getUserId());
        //log.info("sessionsId - " + sessionsId.toString());
//      查查查
        for (Integer i:sessionsId) {
            SessionLastMessage sessionLastMessage = new SessionLastMessage();
            sessionLastMessage.setSessionId(i);
            List<Friend> friendList = sessionMapper.selectSessionFriends(i,user.getUserId());
            //log.info("friendList - "+friendList.toString());
            sessionLastMessage.setFriends(friendList);
            String lastMessage = sessionMapper.selectSessionLastMessage(i,user.getUserId());
            //log.info("lastMaessage - " + lastMessage);
            if (lastMessage==null){
                lastMessage = "";
            }
            sessionLastMessage.setLastMessage(lastMessage);
            sessionLastMessages.add(sessionLastMessage);
        }
        return new Result<>(200,"查询成功",sessionLastMessages);
    }

//    创建一个新会话
//    这里的toUserId就是实现多人聊天的第一步 拿到的UerId是一个数组
    @RequestMapping("/session")
    private Result<Map> addSession(Integer toUserId,HttpServletRequest request){
        Map<String,Integer> resp = new HashMap<>();
//        新增一个回话 拿到回话id
        SessionLastMessage sessionLastMessage = new SessionLastMessage();
        sessionMapper.addASession(sessionLastMessage);
        int sessionId = sessionLastMessage.getSessionId();
        //log.info("新建的session sessionId - " + sessionId);
//        进行会话_用户表的插入
//          1.把登录用户信息插入
        String jwtToken = request.getHeader(Constant.REQUEST_TOKEN_KEY);
        //log.info("jwtToken - "+jwtToken);

        User loginUser = jwtUtils.getUserByToken(jwtToken);
        userSessionMapper.add(sessionId, loginUser.getUserId());
//          2.再把to用户信息插入
        userSessionMapper.add(sessionId, toUserId);
        resp.put("sessionId",sessionId);
        log.info("新会话创建成功 sessionId - " +sessionId);
        return new Result<>(Constant.SUCCESS_CODE,"新会话创建成功",resp);
    }
//    获取历史消息
    @RequestMapping("/message")
    private Result<List> getHistoryMessages(Integer sessionId,HttpServletRequest request){
        List<Message> list;
        String jwtToken = request.getHeader(Constant.REQUEST_TOKEN_KEY);
        User loginUser = jwtUtils.getUserByToken(jwtToken);
        list = sessionMapper.getHistoryMessage(sessionId, loginUser.getUserId());

        //log.info("历史消息" + list.toString());
        //list.get(0).getPostTime().
        return new Result<>(Constant.SUCCESS_CODE,"查询历史消息成功",list);
    }
//    删除一个回话里的消息
}
